import { validatePassword, generateSuggestion } from './passwordValidator.js';

document.addEventListener('DOMContentLoaded', function() {
    const usernameInput = document.getElementById('username') as HTMLInputElement;
    const passwordInput = document.getElementById('password') as HTMLInputElement;
    const validateBtn = document.getElementById('validateBtn') as HTMLButtonElement;
    const suggestBtn = document.getElementById('suggestBtn') as HTMLButtonElement;
    const resultDiv = document.getElementById('result') as HTMLDivElement;
    const strengthMeter = document.getElementById('strengthMeter') as HTMLDivElement;

    // 验证密码并显示结果
    function validateAndShowResult() {
        const username = usernameInput.value;
        const password = passwordInput.value;
        
        const result = validatePassword(password, username);
        
        resultDiv.style.display = 'block';
        resultDiv.className = 'result ' + (result.isValid ? 'valid' : 'invalid');
        
        let reasonsHtml = '';
        if (result.reasons && result.reasons.length > 0) {
            reasonsHtml = `
                <div class="reasons">
                    <p>安全验证失败:</p>
                    ${result.reasons.map(reason => `
                        <div class="reason-category">
                            <strong>不符合${reason.category}要求:</strong>
                            <ul>
                                ${reason.details.map(detail => `<li>${detail}</li>`).join('')}
                            </ul>
                        </div>
                    `).join('')}
                </div>
            `;
        }
        
        resultDiv.innerHTML = `
            <strong>${result.message}</strong>
            ${reasonsHtml}
            ${result.suggestion ? `<p class="suggestion">${result.suggestion}</p>` : ''}
        `;
        
        updateStrengthMeter(password);
    }

    // 更新密码强度指示器
    function updateStrengthMeter(password: string) {
        let strength = 0;
        
        // 长度检查
        if (password.length >= 8) strength += 25;
        if (password.length >= 12) strength += 15;
        
        // 复杂度检查
        if (/[A-Z]/.test(password)) strength += 15;
        if (/[a-z]/.test(password)) strength += 15;
        if (/\d/.test(password)) strength += 15;
        if (/[^A-Za-z0-9]/.test(password)) strength += 15;
        
        strength = Math.min(strength, 100);
        
        strengthMeter.style.width = strength + '%';
        strengthMeter.style.backgroundColor = 
            strength < 40 ? '#ff4d4d' :
            strength < 70 ? '#ffa64d' : '#4CAF50';
    }

    // 获取建议密码并复制到剪贴板
    function getSuggestedPassword() {
        // 如果已有验证结果且不合规，复制结果中的建议密码
        if (resultDiv.style.display === 'block' && resultDiv.classList.contains('invalid')) {
            const suggestionElement = resultDiv.querySelector('.suggestion');
            if (suggestionElement) {
                const suggestion = suggestionElement.textContent?.replace('建议使用: ', '') || '';
                navigator.clipboard.writeText(suggestion).then(() => {
                    const originalText = suggestBtn.textContent;
                    suggestBtn.textContent = '已复制!';
                    setTimeout(() => {
                        suggestBtn.textContent = originalText;
                    }, 2000);
                });
                return;
            }
        }

        // 否则基于当前密码和用户名生成改进建议
        const currentPassword = passwordInput.value;
        const username = usernameInput.value;
        const suggestion = generateSuggestion(currentPassword, username);
        passwordInput.value = suggestion;
        navigator.clipboard.writeText(suggestion).then(() => {
            const originalText = suggestBtn.textContent;
            suggestBtn.textContent = '已复制!';
            setTimeout(() => {
                suggestBtn.textContent = originalText;
            }, 2000);
        });
        validateAndShowResult();
    }

    // 事件监听
    validateBtn.addEventListener('click', validateAndShowResult);
    suggestBtn.addEventListener('click', getSuggestedPassword);
    
    // 实时验证（防抖处理）
    let debounceTimer: any;
    passwordInput.addEventListener('input', function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            updateStrengthMeter(passwordInput.value);
        }, 300);
    });
});
